package medium;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class T22 {
    public List<String> generateParenthesis(int n) {
        List list = new ArrayList<String>();
        dfs(n, list);
        return list;
    }

    public void dfs(int val, List<String> list) {
        if (val == 0) {
            return;
        }
        dfsL("", 1, 0, list, val);
    }

    public void dfsL(String s, int x, int y, List<String> list, int n) {
        s += "(";

        if (x != n) {
            dfsL(s, x + 1, y, list, n);
            if (x > y) {
                dfsR(s, x, y + 1, list, n);
            }
        } else {
            if (y != n) {
                dfsR(s, x, y + 1, list, n);
            }
        }
    }

    public void dfsR(String s, int x, int y, List<String> list, int n) {
        s += ")";
        if (x != n) {
            dfsL(s, x + 1, y, list, n);
            if (x > y) {
                dfsR(s, x, y + 1, list, n);
            }
        } else {
            if (y != n) {
                dfsR(s, x, y + 1, list, n);
            }
        }
        if (x == n && y == n) {
            list.add(s);
        }

    }
}

